<template>
  <div>
    <CloudUpload
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :action="actionUrl"
      pictureUploadText="测试上传"
      :before-upload="beforeUpload"
      @change="handleChange"
      @preview="handlePreview"
    >
    </CloudUpload>
    <span>
      切换开关改变上传地址，上传失败
      <CloudSwitch v-model="checked"></CloudSwitch>
    </span>
  </div>
</template>

<script>
export default {
  title: '7.用户头像(图片)',
  subTitle: '点击上传用户头像，并使用 beforeUpload 限制用户上传的图片格式和大小。beforeUpload 的返回值可以是一个 Promise 以支持异步处理，如服务端校验等',
  data() {
    return {
      loading: false,
      imageUrl: '',
      checked: false
    }
  },
  computed: {
    getLoading() {
      return {
        show: this.loading,
        size: 'small',
        style: 'background: transparent;'
      }
    },
    actionUrl() {
      return this.checked ? 'http://172.31.15.10:53000/mock/89/designCenter/app/uploadPic' : 'https://www.mocky.io/v2/5cc8019d300000980a055e76'
    }
  },
  methods: {
    getBase64(img, callback) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    },

    handleChange(info) {
      this.loading = (info.file.status === 'uploading')
      if (info.file.status === 'uploading') {
        return;
      } else if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
        });
      } else {
        //this.$message.error(`${info.file.name} 文件上传失败.`);
      }
    },

    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('你只能上传JPG/PNG文件!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片大小必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>